<template>
  <div class="page-container">

    <a-card style="width: 100%">
      <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form"
              :model="formState"
              style="width: 100%; display: flex;">
        <a-row :gutter="16">
          <a-col>
            <a-form-item name="carType" label="车型" style="margin-bottom: 0;">
              <a-select v-model:value="formState.carType" show-search style="width: 130px;"
                        :options="cardTypeOptions"
                        placeholder="请选择车型" allowClear></a-select>
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item name="vin" label="VIN">
              <a-input placeholder="请输入VIN" style="width: 130px;"></a-input>
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item name="name" label="设备名称">
              <a-input placeholder="请输入设备名称" style="width: 130px;"></a-input>
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item name="clientType" label="客户端类型">
              <a-select v-model:value="formState.clientType" placeholder="请选择客户端类型"
                        show-search style="width: 130px;"
                        :options="clientTypeOptions" allowClear></a-select>
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item name="os" label="操作系统">
              <a-select v-model:value="formState.os" placeholder="请选择操作系统" show-search
                        style="width: 130px;"
                        :options="osOptions" allowClear></a-select>
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item name="status" label="设备状态">
              <a-select v-model:value="formState.status" placeholder="请选择设备状态" show-search
                        style="width: 130px;"
                        :options="statusOptions" allowClear></a-select>
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item name="connectionStatus" label="连接状态">
              <a-select v-model:value="formState.connectionStatus" placeholder="请选择连接状态"
                        show-search
                        style="width: 130px;" :options="connectionStatusOptions"
                        allowClear></a-select>
            </a-form-item>
          </a-col>
          <a-col>
            <a-form-item>
              <a-button type="primary">搜索</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card style="width: 100%; margin: 12px 0 12px 0; min-height: calc(100vh - 300px);">
      <a-row :gutter="18">
        <a-col>
          <a-button type="primary" @click="()=> router.push('/devices/device-list/add-device') ">新增设备</a-button>
        </a-col>
        <a-col>
          <a-button>批量删除</a-button>
        </a-col>
      </a-row>

      <br />
      <a-table :columns="columns" :data-source="devicesData.list" bordered
               :row-selection="rowSelection" :loading="loading"
               style="width: 100%;" :scroll="{ x: 1000, y: 480 }"
               @resizeColumn="handleResizeColumn"
               :pagination="{defaultCurrent: 1, defaultPageSize: 10, current: devicesData.pageNum, pageSize: devicesData.pageSize, onChange: (pageNum:number, pageSize:number) => {devicesData.pageNum = pageNum;devicesData.pageSize = pageSize; getDevicesData()},showSizeChanger: true, showQuickJumper: true, total: devicesData.total, showTotal: (total:number) => `共${total}条`}">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'deviceId'">
            <a @click="router.push('/devices/device-list/device-detail/' + record.deviceId)">
              {{ record.deviceId || '-' }}
            </a>
          </template>
          <template v-if="column.key === 'status'">
                  <span>
                    <a-tag
                      :color="record.status === 'used' ? 'green' : 'red'">{{ record?.status === 'used' ? '在用' : '弃用'
                      }}</a-tag>
                  </span>
          </template>
          <template v-if="column.key === 'deviceConnectionStatus'">
                  <span>
                    <a-tag
                      :color="record.deviceConnectionStatus === 1 ? 'green' : 'red'">{{ record?.deviceConnectionStatus === 1 ?
                      '在线'
                      : '离线' }}</a-tag>
                  </span>
          </template>
          <template v-if="column.key === 'executedCommand'">
                  <span>
                    <a
                      @click="()=> { onExecutedCommand(record) }">执行命令</a>
                  </span>
          </template>
          <template v-if="column.key === 'action'">
                  <span>
                    <a>编辑</a>
                    <a-divider type="vertical" />
                    <a>下载证书</a>
                    <a-divider type="vertical" />
                    <a>启用</a>
                    <a-divider type="vertical" />
                    <a>弃用</a>
                    <a-divider type="vertical"/>
                    <a  @click="handleDelete(record)" >删除</a>
                  </span>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:open="modelOpen"
      title="执行命令"
      width="600px"
      min-height="300px"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      ok-text="确定"
      cancel-text="取消"
    >
      <div style="margin-top:24px">
        <a-form
          :model="executeCommandFormState"
          name="basic"
          autocomplete="off"
          size="large"
          :label-col="{ span: 4 }"
          ref="executeCommandFormRef"
        >

          <a-form-item label="设备名称">
            {{executeCommandFormState.deviceName}}
          </a-form-item>

          <a-form-item label="设备ID">
            {{executeCommandFormState.deviceId}}
          </a-form-item>


          <a-form-item
            label="执行指令"
            name="command"
            :rules="[{ required: true, message: '请选择执行的指令' }]"
          >
            <a-select v-model:value="executeCommandFormState.command" show-search
                      :options="executeCommandsOptions"
                      placeholder="请选择执行的指令" allowClear></a-select>
          </a-form-item>

          <a-form-item
            v-if="executeCommandFormState.command === 'start_data_collection'"
            label="控制器列表"
            name="sensor_list"
            :rules="[{ required: true, message: '请选择采集控制器' }]"
          >
            <a-select v-model:value="executeCommandFormState.sensor_list" mode="multiple" show-search
                      :options="SensorOptions"
                      placeholder="请选择传感器" allowClear></a-select>
          </a-form-item>

          <a-form-item
            v-if="executeCommandFormState.command === 'start_data_collection'"
            label="采集时间"
            name="duration"
            :rules="[{ required: true, message: '请输入采集时间' }]"
          >
            <a-input-number v-model:value="executeCommandFormState.duration" placeholder="请输入采集时间" >
              <template #addonAfter>
                <a-select v-model:value="executeCommandFormState.duration_unit" placeholder="请选择时间单位" allowClear>
                  <a-select-option value="ms">毫秒</a-select-option>
                  <a-select-option value="s">秒</a-select-option>
                  <a-select-option value="m">分</a-select-option>
                  <a-select-option value="h">时</a-select-option>
                </a-select>
              </template>
            </a-input-number>
          </a-form-item>

        </a-form>
      </div>
    </a-modal>

  </div>
</template>

<script lang="ts" setup>
import { computed, onActivated, onMounted, reactive, ref } from 'vue'
import { devicesApi } from '@/api/devices'
import router from '@/router'
import { useDeviceSelectOptions } from '@/composables/useDeviceSelectOptions.ts'
import { message } from 'ant-design-vue'
import notification from 'ant-design-vue/es/notification'

const { osOptions, cardTypeOptions, clientTypeOptions, connectionStatusOptions, statusOptions,
  executeCommandsOptions, SensorOptions } = useDeviceSelectOptions()

interface ExecuteCommandParam {
  deviceId?: string,
  deviceName?: string,
  command?: string,
  sensor_list?: string[],
  duration?: number,
  duration_unit?: string,
}

const modelOpen = ref<boolean>(false)
const executeCommandFormRef = ref()
const confirmLoading = ref<boolean>(false)
const loading = ref<boolean>(false)


const executeCommandFormState = reactive<ExecuteCommandParam>({
  deviceId: '',
  deviceName: '',
  command: '',
  sensor_list: [],
  duration: 0,
  duration_unit: 'ms',
})
const onExecutedCommand = (record: any) =>  {
  executeCommandFormState.deviceId = record.deviceId
  executeCommandFormState.deviceName = record.deviceName
  modelOpen.value = true
}
const handleOk = () => {
  confirmLoading.value = true
  // 执行命令
  executeCommandFormRef.value.validate().then(async () => {
    const res = await devicesApi.executeCommand({
      deviceId: executeCommandFormState.deviceId,
      command: executeCommandFormState.command,
      commandParam: {
        duration: executeCommandFormState.duration,
        duration_unit: executeCommandFormState.duration_unit,
        sensor_list: executeCommandFormState.sensor_list,
      },
    })

    if (res?.code === 200) {
      notification.success({
        message: '发送命令成功',
      })
      confirmLoading.value = false
      executeCommandFormRef.value.resetFields()
      modelOpen.value = false
    } else {
      notification.error({
        message: res?.message || '发送命令失败',
        description: res?.errors || ''
      })
      confirmLoading.value = false
    }
  })
}

const handleCancel = () => {
  modelOpen.value = false
  executeCommandFormRef.value.resetFields()
}

const columns = [
  {
    title: 'ID',
    dataIndex: 'deviceId',
    key: 'deviceId',
    ellipsis: true,
    width: 250,
  },
  {
    title: '名称',
    dataIndex: 'deviceName',
    key: 'deviceName',
    width: 150,
    resizable: true,
  },
  {
    title: '车型',
    dataIndex: 'productId',
    key: 'productId',
    width: 100,
    ellipsis: true,
  },
  {
    title: 'VIN',
    dataIndex: 'deviceVin',
    key: 'deviceVin',
    width: 200,
    ellipsis: true,
  },
  {
    title: '客户端ID',
    dataIndex: 'deviceClientId',
    key: 'deviceClientId',
    ellipsis: true,
    width: 150
  },
  {
    title: '连接状态',
    dataIndex: 'deviceConnectionStatus',
    key: 'deviceConnectionStatus',
    width: 100
  },
  {
    title: '客户端类型',
    dataIndex: 'deviceClientType',
    key: 'deviceClientType',
    ellipsis: true,
    width: 150
  },
  {
    title: '版本',
    dataIndex: 'version',
    ellipsis: true,
    key: 'version',
    width: 100
  },
  {
    title: '操作系统',
    dataIndex: 'deviceOs',
    ellipsis: true,
    key: 'deviceOs',
    width: 150
  },
  {
    title: '操作系统版本',
    dataIndex: 'deviceOsVersion',
    ellipsis: true,
    key: 'deviceOsVersion',
    width: 200
  },
  {
    title: 'IP地址',
    dataIndex: 'deviceIp',
    ellipsis: true,
    key: 'deviceIp',
    width: 200
  },
  {
    title: 'MAC地址',
    dataIndex: 'deviceMac',
    ellipsis: true,
    key: 'deviceMac',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'deviceStatus',
    key: 'deviceStatus',
    width: 100
  },
  {
    title: '创建人',
    dataIndex: 'createdUserId',
    ellipsis: true,
    key: 'createdUserId',
    width: 150
  },
  {
    title: '创建时间',
    key: 'createdTime',
    dataIndex: 'createdTime',
    ellipsis: true,
    width: 180
  },
  {
    title: '最近上线时间',
    key: 'lastConnectTime',
    dataIndex: 'lastConnectTime',
    ellipsis: true,
    width: 180
  },
  {
    title: '执行命令',
    key: 'executedCommand',
    width: 100,
    fixed: 'right'
  },
  {
    title: '操作',
    key: 'action',
    width: 280,
    fixed: 'right'
  }
]


const devicesData = reactive({
  list: [],
  total: 0,
  pageNum: 1,
  pageSize: 10
})

function handleResizeColumn(w, col) {
  col.width = w;
}

const getDevicesData = async () => {
  loading.value = true
  const res = await devicesApi.ListDevicePage({
    pageNum: devicesData.pageNum,
    pageSize: devicesData.pageSize
  })
  console.log('res', res);
  if (res && res?.code === 200) {
    devicesData.list = res?.data?.list
    devicesData.total = res?.data?.total
    devicesData.pageNum = res?.data?.pageNum
    devicesData.pageSize = res?.data?.pageSize
    devicesData.list = res?.data?.records
  } else {
    notification.error({ message: res?.message || '获取数据失败'});
  }
  loading.value = false
}


onActivated(() => {
  getDevicesData()
})


const state = reactive<{
  selectedRowKeys: string | number[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false
})

const onSelectChange = (selectedRowKeys: string | number[]) => {
  console.log('selectedRowKeys changed: ', selectedRowKeys)
  state.selectedRowKeys = selectedRowKeys
}
const rowSelection = computed(() => ({
  selectedRowKeys: state.selectedRowKeys,
  onChange: onSelectChange
}))

const formState = reactive({
  name: '',
  vin: '',
  carType: '',
  status: '',
  connectionStatus: '',
  clientType: '',
  os: '',
  osVersion: '',
  ip: '',
  mac: ''
})


const handleDelete = async (record: string)  => {
  console.log('handleDelete', record)
  const res = await devicesApi.deleteDevice({id: record?.deviceId});
  console.log(res);
  if (res?.code === 200) {
    message.success({ content: '删除成功'});
    getDevicesData();
  } else {
    message.error({ content: res?.message});
  }
}




</script>

<style scoped lang="less">
.page-container {

}
</style>
